import Cookie from 'js-cookie'
import { createStore } from 'vuex'

export default createStore({
  state: {
    //控制左侧菜单显示隐藏
    isCollapse: true,
    //面包屑和tab数据
    currentMenu: [
      {
        path: '/',
        name: 'home',
        label: '首页',
        icon: 'HomeFilled',
        url: 'Home/Home'
      }
    ],
    //登录之后的路由
    Menu: [],
    token:''
  },
  mutations: {
    //控制左侧菜单收起
    updateIsCollapse(state) {
      state.isCollapse = !state.isCollapse
    },
    //更新面包屑数据
    selectMenu(state, val) {
      //判断
      // val.name = 'home' ? (state.currentMenu = null) : (state.currentMenu = val)
      //判断数据是否为首页
      if (val.name !== 'home') {
        // findIndex表示如果存在则返回当前数据的索引，不存在则返回-1
        const index = state.currentMenu.findIndex(item => item.name === val.name)
        //如果不存在
        if (index === -1) {
          state.currentMenu.push(val)
        }
      }
    },
    //根据name删除tab栏
    closeTab(state, val) {
      //  state.currentMenu = state.currentMenu.filter(item => item.name !== val.name)
      let res = state.currentMenu.findIndex(item => item.name === val.name)

      state.currentMenu.splice(res, 1)
    },

    //根据登录用户名的不同展现不同的路由
    setMenu(state, val) {
      state.Menu = val
      //进行本地存储
      localStorage.setItem('menu', JSON.stringify(val))
    },
    //动态注册路由
    addMenu(state, router) {
      if (!localStorage.getItem('menu')) return
      const menu = JSON.parse(localStorage.getItem('menu'))
      state.Menu = menu

      const menuArray = []
      menu.forEach(item => {
        //如果路由中存在子路由
        if (item.children) {
          item.children = item.children.map(item => {
            let url = `../view/${item.url}.vue`
            item.component = () => import(url)
            return item
          })
          menuArray.push(...item.children)
        } else {
          //不存在子路由
          let url = `../view/${item.url}.vue`
          item.component = () => import(url)
          menuArray.push(item)
        }
      })
        //动态路由匹配
      menuArray.forEach(item => {
        router.addRoute('Main', item)
      })
    },

    //退出登录，清除本地存储
    cleanMenu(state){
      state.Menu = []
      localStorage.removeItem('menu')
    },
    //设置token
    setToken(state,val){
      state.token = val
      Cookie.set('token',val)
    },
    //清除token
    clearToken(state){
      state.token = ''
      Cookie.remove('token')
    },
    //获取token
    getToken(state){
    state.token = state.token || Cookie.get('token')
    }
  }
})
